<?php

namespace app\common\model\Card;

use think\Model;

class Card extends Model
{
    // 名片表
    protected $table = 'pre_card';

    // 自动写入时间
    protected $autoWriteTimestamp = false;

    // 创建时间 => 注册时间
    protected $createTime = 'createtime';

    // 更新时间
    protected $updateTime = false;

    protected $append = [
        'region_text',
        'avatar_cdn'
    ];

    // 地区字段
    public function getRegionTextAttr($value, $data)
    {
        $ReogionList = [];

        if (!empty($data['province'])) {
            $ReogionList[] = model('Region')->where(['code' => $data['province']])->value('name');
        }

        if (!empty($data['city'])) {
            $ReogionList[] = model('Region')->where(['code' => $data['city']])->value('name');
        }

        if (!empty($data['district'])) {
            $ReogionList[] = model('Region')->where(['code' => $data['district']])->value('name');
        }

        return implode('-', $ReogionList);
    }

    // 头像
    public function getAvatarCdnAttr($value, $data)
    {
        $avatar = @is_file('.' . $data['avatar']) ? $data['avatar'] : '/static/home/res/images/avatar/default.png';

        // $cdn = config('cdn');

        $cdn = model('Config')->where(['key' => 'SiteUrl'])->value('value');

        return $cdn . $avatar;
    }

    // 关联查询
    public function type()
    {
        return $this->belongsTo('app\common\model\Card\Type', 'typeid', 'id', [], 'LEFT')->setEagerlyType(0);
    }
}
